from drf_spectacular.openapi  import AutoSchema
from drf_spectacular.generators  import SchemaGenerator 
from drf_spectacular.plumbing  import get_doc 
 
def custom_preprocessing_hook(endpoints):
    """自定义API端点预处理（路由分组/过滤）"""
    return [
        (path, path_regex, method, callback) 
        for path, path_regex, method, callback in endpoints 
        if not path.startswith('/schema/') 
    ]
 
class CustomAutoSchema(AutoSchema):
    """增强的自动Schema生成器"""
    
    def get_summary(self):
        """智能提取摘要：优先取方法docstring，其次取类docstring"""
        method_doc = get_doc(self.method) 
        if method_doc:
            return method_doc.split('\n')[0].strip() 
        return get_doc(self.view.__class__).split('\n')[0].strip() 
 
    def map_serializer(self, serializer, direction):
        """自定义序列化器映射逻辑"""
        result = super().map_serializer(serializer, direction)
        if hasattr(serializer, 'Meta') and hasattr(serializer.Meta, 'example'):
            result['example'] = serializer.Meta.example  
        return result 
 
class CustomSchemaGenerator(SchemaGenerator):
    """带业务标签的Schema生成器"""
    
    def get_schema(self, *args, **kwargs):
        schema = super().get_schema(*args, **kwargs)
        
        # 动态添加标签分组 
        schema['tags'] = [
            {'name': 'sys', 'description': '系统管理接口'},
        ]
        
        # 全局添加Bearer认证 
        schema['components']['securitySchemes'] = {
            'Bearer': {'type': 'http', 'scheme': 'bearer'}
        }
        return schema 